package com.hifar.test.archive.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.hifar.fw.utils.lang.DateUtils;
import com.hifar.test.archive.mapper.HfEnvArchiveMapper;
import com.hifar.test.archive.pojo.HfEnvArchive;
import com.hifar.test.archive.pojo.HfEnvArchiveVo;
import com.hifar.test.archive.service.IHfEnvArchiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.RequestConver;

/**
 * <p>
 * 文件管理 服务实现类
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-09 15:10:00
 */
@Service
public class HfEnvArchiveServiceImpl extends ServiceImpl<HfEnvArchiveMapper, HfEnvArchive> implements IHfEnvArchiveService {

	@Override
	public BusiResponse exportExcel(Map<String, Object> pageInfo) {
		BusiResponse busiResponse = new BusiResponse();
		String ids = (String) pageInfo.get("ids");

		String operationType = (String) pageInfo.get("operationType");

		if (StringUtils.isNotBlank(operationType) && (operationType.equals("template"))) {
			ExcelTemplateUtil.exportExcelTemplate(busiResponse, HfEnvArchive.class, "导入模板", "文件管理导入数据");
			return busiResponse;
		} else {
			QueryWrapper<HfEnvArchive> postParam = RequestConver.getPostParam(pageInfo);
			postParam.ne("del_flag", 1);
			postParam.orderByDesc("create_time");
			if (StringUtils.isNotBlank(ids)) {
				postParam.in("id", ids);
			}
			List<HfEnvArchive> dataList = this.list(postParam);
			if (dataList != null && dataList.size() > 0) {
				ExcelTemplateUtil.exportExcel(busiResponse, dataList, HfEnvArchive.class, "文件管理数据", "文件管理导出");
			} else {
				ExcelTemplateUtil.exportExcelTemplate(busiResponse, HfEnvArchive.class, "文件管理数据", "文件管理导出");
			}
			return busiResponse;
		}

	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public BusiResponse importExcel(MultipartFile file) throws Exception {
		if (file != null && !file.isEmpty()) {
			List<HfEnvArchive> importExcel = ExcelTemplateUtil.importExcel(file.getInputStream(), HfEnvArchive.class);
			List<HfEnvArchive> importExcelList = new ArrayList<HfEnvArchive>();
			if (importExcel != null && importExcel.size() > 0) {
				for (HfEnvArchive bean : importExcel) {
					bean.setId(IdUtils.uuid32());
					bean.setDelFlag(0);
					//if(!bean.getName().equals("")) {
					importExcelList.add(bean);
					//}
				}
				this.saveBatch(importExcelList);
				return BusiResponse.ok("导入成功！");
			}
		}
		return BusiResponse.error("导入失败，原因未知！");
	}

	@Override
	public String generateLevel1Excel(HfEnvArchive archive) {
		String returnPath = "";

		QueryWrapper<HfEnvArchiveVo> queryWrapper = new QueryWrapper<HfEnvArchiveVo>();
		queryWrapper.ne("del_flag", 1);
		queryWrapper.ne("statisic_excel", 1);
		queryWrapper.like("search_flag_path", archive.getSearchFlagPath());
		queryWrapper.orderByAsc("level_num", "create_time", "search_flag");

		String filePath;
		String filePathDisplay;
		String fileTypeDisplay;
		String createTimeDisplay;

		Page<HfEnvArchiveVo> rowPage = new Page<>(1, 100);
		Page<HfEnvArchiveVo> pageObj = this.getBaseMapper().selectHfEnvArchiveVoPage(rowPage, queryWrapper);
		List<HfEnvArchiveVo> dataList = new ArrayList<HfEnvArchiveVo>();
		if (pageObj != null) {
			if (pageObj.getRecords() != null) {
				dataList.addAll(pageObj.getRecords());
			}
			//分页查询所有的数据  start
			for (int i = 2; i < pageObj.getPages(); i++) {
				rowPage = new Page<>(i, 100);
				pageObj = this.getBaseMapper().selectHfEnvArchiveVoPage(rowPage, queryWrapper);
				if (pageObj != null) {
					if (pageObj.getRecords() != null) {
						dataList.addAll(pageObj.getRecords());
					}
				}
			}
			//分页查询所有的数据  end
		}
		queryWrapper = new QueryWrapper<HfEnvArchiveVo>();
		queryWrapper.ne("del_flag", 1);
		queryWrapper.eq("file_type", 1);
		queryWrapper.ne("statisic_excel", 1);
		queryWrapper.like("search_flag_path", archive.getSearchFlagPath());
		queryWrapper.orderByAsc("search_flag");
		List<HfEnvArchiveVo> dirList = this.getBaseMapper().selectHfEnvArchiveVoList(queryWrapper);
		final Map<String, HfEnvArchiveVo> dirMap = dirList.stream()
				.collect(Collectors.toMap(item -> item.getSearchFlag().toString(),
						item -> item,
						(o1, o2) -> o1));

		dataList.stream().forEach(item -> {
			Date createTime = item.getCreateTime();
			item.setCreateTimeDisplay(DateUtils.formatTime(createTime, DateUtils.YYYY_MM_DD));

			int fileType = item.getFileType();
			if (fileType == 1) {
				item.setTypeDisplay("目录");
			} else {
				item.setTypeDisplay("文件");
			}
			//如果是文件计算文件大小 start
			if (fileType == 2) {
				double fileSize = item.getFileSize();
				double sizeEnd;
				String result = "";
				DecimalFormat df = new DecimalFormat("#.00");
				if (fileSize < 1000) {
					item.setFileSizeDisplay(fileSize + "b");
				} else if (fileSize >= 1000 && fileSize <= 1000 * 1000) {
					sizeEnd = fileSize / 1000;
					result = df.format(sizeEnd);
					item.setFileSizeDisplay(result + "K");
				} else if (fileSize >= 1000 * 1000 && fileSize <= 1000 * 1000 * 1000) {
					sizeEnd = fileSize / (1000 * 1000);
					result = df.format(sizeEnd);
					item.setFileSizeDisplay(result + "M");
				} else if (fileSize >= 1000 * 1000 * 1000) {
					sizeEnd = fileSize / (1000 * 1000 * 1000);

					result = df.format(sizeEnd);
					item.setFileSizeDisplay(result + "G");
				}
			}
			//如果是文件计算文件大小 end
			String searchFlagPath = item.getSearchFlagPath();
			StringBuffer sb = new StringBuffer();
			String[] arr = searchFlagPath.split("_");
			sb.append("/");
			HfEnvArchiveVo vo = null;
			for (int i = 1; i < arr.length; i++) {
				vo = dirMap.get(arr[i]);
				if (vo != null) {
					sb.append(vo.getFileName() + "/");
				}
			}
			sb.deleteCharAt(sb.lastIndexOf("/"));
			if (fileType == 1) {
				item.setFilePathDisplay(sb.toString());
			} else if (fileType == 2) {
				item.setFilePathDisplay(sb.toString() + "/" + item.getFileName());
			}
		});

		if (dataList != null && dataList.size() > 0) {
			try {
				String fileName = IdUtils.uuid32();
				returnPath = ExcelTemplateUtil.exportExcel(dataList, HfEnvArchiveVo.class, fileName, archive.getFileName());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return returnPath;
	}

}
